package ch.rheintalconnection.sysventory.presentation;


import ch.rheintalconnection.sysventory.businessServices.LoginService;
import ch.rheintalconnection.sysventory.domain.User;
import ch.rheintalconnection.sysventory.presentation.panels.ApplicationPanel;
import ch.rheintalconnection.sysventory.presentation.panels.LoginPanel;

import com.vaadin.ui.LoginForm;
import com.vaadin.ui.LoginForm.LoginEvent;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.Notification;

public class MainApplicationHandler implements LoginForm.LoginListener{

	private static final long serialVersionUID = 5523990723572062800L;
	
	Window mainWindow;
	LoginPanel loginPanel;
	ApplicationPanel applicationPanel;
	Bootstrapper bootstrapper;
	LoginService loginService;
	
	public MainApplicationHandler(Window window) {
		mainWindow = window;
		bootstrapper = new Bootstrapper();
		loginPanel = new LoginPanel(this);
		applicationPanel = new ApplicationPanel(bootstrapper.getScanningService(), bootstrapper.getDataService(), bootstrapper.getDataReader(), this);
		loginService = new LoginService(bootstrapper.getDataReader());
		activateLoginPanel();
	}
	
	public void activateLoginPanel(){
		mainWindow.removeAllComponents();
		mainWindow.addComponent(loginPanel);
	}
	
	public void activateApplicationPanel(User user){
		mainWindow.removeAllComponents();
		applicationPanel.setUser(user);
		mainWindow.addComponent(applicationPanel);
	}

	public void onLogin(LoginEvent event) {
		String username = event.getLoginParameter("username");
		String password = event.getLoginParameter("password");
		
		
		if(loginService.validate(username, password)){
			try {
				User user = loginService.getUser(username, password);
				activateApplicationPanel(user);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}else{
			mainWindow.showNotification("Benutzername oder Passwort ist ungültig. ",Notification.TYPE_WARNING_MESSAGE);
		}
		
	}
}
